<template>
  <div class="app-container">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="电桩信息" name="first">
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          v-show="showSearch"
          label-width="90px"
        >
          <el-form-item label="电桩类型">
            <el-select
              v-model="queryParams.equipmentType"
              placeholder="请选择电桩类型"
              filterable
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="dict in dict.type.charge_stake_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="站点名称">
            <el-select
              v-model="queryParams.stationName"
              placeholder="请选择站点名称"
              filterable
              clearable
              style="width: 100%"
              @change="getStaion"
            >
              <el-option
                v-for="item in stationList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="设备类型">
            <el-select
              v-model="queryParams.equipmentType"
              placeholder="请选择设备类型"
              filterable
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="dict in dict.type.charge_stake_equip_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              >
              </el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['business:stake:add']"
              >新增</el-button
            >
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="true" @click="handleUpdate"
              v-hasPermi="['business:stake:edit']">修改</el-button>
          </el-col> -->
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['business:stake:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['business:stake:export']"
              >导出</el-button
            >
          </el-col>
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>

        <el-table
          v-loading="loading"
          :data="stakeList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="电桩编号" align="center" prop="equipmentId" />
          <el-table-column
            label="站点名称"
            align="center"
            prop="stationName"
            show-overflow-tooltip
          />
          <!-- <el-table-column label="设备类型" align="center" prop="equipmentType">
            <template slot-scope="scope">
              <dict-tag
                :options="dict.type.charge_stake_equip_type"
                :value="scope.row.equipmentType"
                :show-overflow-tooltip="true"
              />
            </template>
          </el-table-column> -->
          <el-table-column
            label="电桩类型"
            align="center"
            prop="equipmentType"
          >
            <template slot-scope="scope">
              <dict-tag
                :options="dict.type.charge_stake_equip_type"
                :value="scope.row.equipmentType"
                :show-overflow-tooltip="true"
              />
            </template>
          </el-table-column>
          <el-table-column label="枪数量/个" align="center" prop="gunNum" />
          <el-table-column label="离线续充" align="center" prop="isOnline">
            <template slot-scope="scope">
              {{ scope.row.isOnline ? "支持" : "不支持" }}
            </template>
          </el-table-column>
          <el-table-column label="电桩状态" align="center" prop="stakeStatus">
            <template slot-scope="scope">
              <dict-tag
                :options="dict.type.charge_stake_status"
                :value="scope.row.stakeStatus"
                :show-overflow-tooltip="true"
              />
            </template>
          </el-table-column>
          <!-- <el-table-column label="故障码" align="center" prop="faultCode" /> -->
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleDetail(scope.row)"
                v-hasPermi="['business:stake:edit']"
                >详情</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['business:stake:remove']"
                style="color: red"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-tab-pane>
      <el-tab-pane label="枪信息" name="second">
        <el-form
          :model="queryParamsInfo"
          ref="queryForm"
          size="small"
          :inline="true"
          v-show="showSearch"
          label-width="90px"
        >
          <el-form-item label="站点名称">
            <el-select
              v-model="queryParamsInfo.stationName"
              placeholder="请选择站点名称"
              filterable
              clearable
              style="width: 100%"
              @change="getStaion"
            >
              <el-option
                v-for="item in stationList"
                :key="item.label"
                :label="item.label"
                :value="item.label"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQueryInfo"
              >搜索</el-button
            >
            <el-button
              icon="el-icon-refresh"
              size="mini"
              @click="resetQueryInfo"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
        <el-table v-loading="loadingInfo" class="qiangTable" :data="gunList">
          <el-table-column label="枪编号" align="center" prop="connectorName" />
          <!-- <el-table-column label="枪自编号" align="center" prop="gunAuto">
            <template slot-scope="scope">
              <div v-if="scope.row.gunAuto">
                {{ scope.row.gunAuto }}
              </div>
              <div
                v-else
                class="edit-box"
                @click="openDialog('gunAuto', scope.row.id)"
              >
                <div class="tableHover">
                  <span>未设置</span>
                  <i class="el-icon-edit-outline"></i>
                </div>
              </div>
            </template>
          </el-table-column> -->

          <el-table-column label="电桩编号" align="center" prop="equipmentId" />
          <!-- <el-table-column label="设备类型" align="center" prop="equipmentType">
            <template slot-scope="scope">
              <dict-tag
                :options="dict.type.charge_stake_equip_type"
                :value="scope.row.equipmentType"
                :show-overflow-tooltip="true"
              />
            </template>
          </el-table-column> -->
          <el-table-column label="站点名称" align="center" prop="stationName" />

          <el-table-column label="当前状态" align="center" prop="connectorStatus">
            <template slot-scope="scope">
              <el-tag
                :type="scope.row.connectorStatus == '1' ? 'success' : 'info'"
                effect="plain"
              >
                {{ scope.row.connectorStatus == "1" ? "充电中" : "待机" }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="totalInfo > 0"
          :total="totalInfo"
          :page.sync="queryParamsInfo.pageNum"
          :limit.sync="queryParamsInfo.pageSize"
          @pagination="getListGun"
        />
      </el-tab-pane>
    </el-tabs>

    <!-- 添加或修改充电桩信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row :gutter="20">
          <el-col :span="12"
            ><el-form-item label="站点名称" prop="stationName">
              <el-select
                v-model="form.stationName"
                placeholder="请选择站点名称"
                filterable
                clearable
                style="width: 100%"
                @change="getStaion"
              >
                <el-option
                  v-for="item in stationList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select> </el-form-item
          ></el-col>
          <el-col :span="12"
            ><el-form-item label="充电桩编码" prop="equipmentId">
              <el-input
                v-model="form.equipmentId"
                placeholder="请输入充电桩编码"
              /> </el-form-item
          ></el-col>
          <el-col :span="12"
            ><el-form-item label="电桩类型" prop="equipmentType">
              <el-select
                v-model="form.equipmentType"
                placeholder="请选择电桩类型"
                filterable
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="dict in dict.type.charge_stake_equip_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                >
                </el-option>
              </el-select> </el-form-item
          ></el-col>
          <el-col :span="12"
            ><el-form-item label="电桩状态" prop="stakeStatus">
              <el-select
                v-model="form.stakeStatus"
                placeholder="请选择电桩状态"
                filterable
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="dict in dict.type.charge_stake_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                >
                </el-option>
              </el-select> </el-form-item
          ></el-col>
          <!-- <el-col :span="12"
            ><el-form-item label="设备类型" prop="equipmentType">
              <el-select
                v-model="form.equipmentType"
                placeholder="请选择设备类型"
                filterable
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="dict in dict.type.charge_stake_equip_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                >
                </el-option>
              </el-select> </el-form-item
          ></el-col> -->
          <el-col :span="12"
            ><el-form-item label="额定功率(kw)" prop="ratedPower">
              <el-input-number
                v-model="form.ratedPower"
                placeholder="请输入额定功率"
                style="width: 100%"
              >
                <template slot="append"><span>KW</span></template>
              </el-input-number>
            </el-form-item></el-col
          >
          <el-col :span="12"
            ><el-form-item label="离线续充" prop="isOnline">
              <el-radio-group v-model="form.isOnline">
                <el-radio :label="'1'" :value="'1'">支持</el-radio>
                <el-radio :label="'0'" :value="'0'">不支持</el-radio>
              </el-radio-group>
            </el-form-item></el-col
          >
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisibleInfo"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="tempForm"
        :model="tempForm"
        label-width="120px"
        :rules="rulesInfo"
      >
        <!-- 桩自编号 -->
        <el-form-item
          v-if="currentType === 'gunAuto'"
          label="枪自编号"
          prop="gunAuto"
        >
          <el-input
            v-model="tempForm.gunAuto"
            placeholder="请输入枪自编号"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancelInfo">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listStake,
  getStake,
  delStake,
  addStake,
  updateStake,
} from "@/api/business/stake";
import { selectChargeStationToSelect } from "@/api/business/chargeStation";
import { listchargeStation } from "@/api/business/chargeStation";
import { listGun, editGun } from "@/api/business/gun";
export default {
  name: "Stake",
  dicts: [
    "charge_speed_type",
    "charge_stake_status",
    "charge_stake_type",
    "charge_stake_equip_type",
  ],
  data() {
    return {
      activeName: "first",
      queryForm: {},
      queryFormInfo: {},
      stationList: [],
      // 遮罩层
      loading: true,
      loadingInfo: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      dialogVisibleInfo: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 充电桩信息表格数据
      stakeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        stationName: null,
        gunCode: null,
        maxPower: null,
        ratedCurrent: null,
        ratedVoltage: null,
        currentType: null,
        stakeStatus: null,
        faultCode: null,
      },
      queryParamsInfo: {
        pageNum: 1,
        pageSize: 10,
        stationName: null,
        gunCode: null,
        maxPower: null,
        ratedCurrent: null,
        ratedVoltage: null,
        currentType: null,
        stakeStatus: null,
        faultCode: null,
      },
      gunId: null,
      currentType: null,
      dialogTitle: null,
      // 表单参数
      form: { isOnline: "0" },
      // 表单校验
      rulesInfo: {
        gunAuto: [
          { required: true, message: "请输入枪自编号", trigger: "blur" },
        ],
      },
      rules: {
        stationName: [
          { required: true, message: "充电站ID不能为空", trigger: "blur" },
        ],
        equipmentId: [
          { required: true, message: "充电枪编码不能为空", trigger: "blur" },
        ],
        stationName: [
          { required: true, message: "站点名称不能为空", trigger: "change" },
        ],

        gunNum: [
          { required: true, message: "充电枪编号不能为空", trigger: "blur" },
        ],

        ratedPower: [
          { required: true, message: "额定功率不能为空", trigger: "blur" },
        ],
        equipmentType: [
          { required: true, message: "请选择电桩类型", trigger: "change" },
        ],
        isOnline: [
          { required: true, message: "请选择续充类型", trigger: "change" },
        ],
        equipmentType: [
          { required: true, message: "请选择设备类型", trigger: "change" },
        ],

        stakeStatus: [
          { required: true, message: "充电桩状态不能为空", trigger: "change" },
        ],
      },
      // 充电站列表
      chargeStationList: [],
      gunList: [],
      totalInfo: 0,
      tempForm: {},
    };
  },
  created() {
    console.log(1233);
    this.getList();
    this.getChargeStationList();
    this.getListchargeStation();
  },
  methods: {
    // 打开弹窗
    openDialog(type, id) {
      this.gunId = id;
      this.currentType = type;
      // 设置弹窗标题
      const titleMap = {
        gunAuto: "编辑枪自编号",
      };
      this.dialogTitle = titleMap[type];

      // 显示弹窗
      this.dialogVisibleInfo = true;
    },

    // 提交表单
    handleSubmit() {
      // 修复：使用正确的表单引用tempForm
      this.$refs.tempForm.validate((valid) => {
        if (valid) {
          editGun({ id: this.gunId, gunAuto: this.tempForm.gunAuto }).then(
            (response) => {
              this.getListGun();
              this.$message.success("修改成功");
              // 关闭弹窗时清空临时表单
              this.tempForm = {};
              this.dialogVisibleInfo = false;
            }
          );
        }
      });
    },
    handleCancelInfo() {
      this.tempForm = {}; // 清空临时表单
      this.$refs.tempForm?.resetFields(); // 重置表单验证状态
      this.dialogVisibleInfo = false;
    },
    handleClick(val) {
      this.activeName = val.name;
      if (this.activeName == "first") {
        this.getList();
      } else {
        this.getListGun();
      }
    },
    getStaion(val) {
      if (val === null) {
        this.form.stationName = ""; // 清空时设置为空字符串
        return;
      }
      const strName = this.stationList.find((item) => item.value == val);
      this.form.stationName = strName ? strName.label : "";
      console.log(this.form.stationName, "this.form.stationName");
    },
    getListchargeStation() {
      listchargeStation().then((response) => {
        console.log(response, 'response')
        this.stationList = response.rows.map((item) => {
          return {
            value: item.stationName,
            label: item.stationName,
          };
        });
      });
    },
    /** 查询枪信息列表 */
    getListGun() {
      this.loadingInfo = true;
      listGun(this.queryParamsInfo).then((response) => {
        console.log(response, "response");
        this.gunList = response.rows;
        this.totalInfo = response.total;
        this.loadingInfo = false;
      });
    },

    /** 查询充电桩信息列表 */
    getList() {
      this.loading = true;
      listStake(this.queryParams).then((response) => {
        this.stakeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 查询充电桩下拉列表信息
    getChargeStationList() {
      selectChargeStationToSelect().then((response) => {
        if (response.code == 200) {
          this.chargeStationList = response.data;
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        equipmentId: null,
        stationName: null,
        equipmentId: null, // 补充清空编码字段
        equipmentType: null,
        stakeStatus: null,
        equipmentType: null,
        ratedPower: null,
        isOnline: "0", // 保留默认值
        stationName: null,
        // 其他字段均重置为null
      };
      this.$refs.form?.resetFields(); // 重置验证状态
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        stationName: null,
        gunCode: null,
        maxPower: null,
        ratedCurrent: null,
        ratedVoltage: null,
        currentType: null,
        stakeStatus: null,
        faultCode: null,
      };
      this.$refs.queryForm?.resetFields();
      this.handleQuery();
    },

    handleQueryInfo() {
      this.queryParamsInfo.pageNum = 1;
      this.getListGun();
    },
    /** 重置按钮操作 */
    resetQueryInfo() {
      this.queryParamsInfo = {
        pageNum: 1,
        pageSize: 10,
        stationName: null,
        gunCode: null,
        maxPower: null,
        ratedCurrent: null,
        ratedVoltage: null,
        currentType: null,
        stakeStatus: null,
        faultCode: null,
      };
      this.$refs.queryForm?.resetFields();
      this.handleQueryInfo();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.equipmentId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加充电桩信息";
    },
    handleDetail(val) {
      console.log(val, "val");
      
      this.$router.push({
        path: "/business/stake-detail/index",
        query: { equipmentId: val.equipmentId },
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.equipmentId != null) {
            updateStake(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStake(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const equipmentIds = row.equipmentId || this.ids;
      this.$modal
        .confirm('是否确认删除充电桩信息编号为"' + equipmentIds + '"的数据项？')
        .then(function () {
          return delStake(equipmentIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "business/stake/export",
        {
          ...this.queryParams,
        },
        `stake_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style lang="scss" scoped>
.qiangTable {
  padding: 20px;

  .edit-box {
    display: flex;
    justify-content: center;
    align-items: center;

    .tableHover {
      width: 80px;
      cursor: pointer;
      transition: all 0.2s;

      &:hover {
        border-bottom: 1px solid #409eff;
        color: #409eff;

        .el-icon {
          color: #409eff;
        }
      }

      span {
        margin-right: 10px;
        transition: color 0.2s;
      }

      .el-icon {
        transition: color 0.2s;
        color: #c0c4cc;
      }
    }
  }
}
</style>
